package edu.ccut.saturn.manager.dict.core;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IDictItemInfo;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnDictionaryManager;

public class UpdateDictParam extends DefaultComponent {

	private static final String PARAM_UPDATE_SQL = "UPDATE saturn_dict SET value = ?, pinyin = ?, parent_code = ? WHERE type = ? AND code = ?";

	@Override
	public void execute(IParameterContext parameterContext) throws Exception {

		String type = (String) parameterContext.getParameterValue(0);
		String code = (String) parameterContext.getParameterValue(1);
		String value = (String) parameterContext.getParameterValue(2);
		String pinyin = (String) parameterContext.getParameterValue(3);
		String parentCode = (String) parameterContext.getParameterValue(4);
		
		if(parentCode == null) {
			parentCode = "";
		}

		String updateSucc = "false";

		PreparedStatement statement = null;
		ResultSet rs = null;

		try {
			statement = parameterContext.getConnection().prepareStatement(
					PARAM_UPDATE_SQL);

			statement.setString(1, value);
			statement.setString(2, pinyin);
			statement.setString(3, parentCode);
			statement.setString(4, type);
			statement.setString(5, code);
			int result = statement.executeUpdate();
			
			if (result == 1) {
				updateSucc = "true";
			}
			
		} catch (SQLException e) {
			logger.error("found exception when execute Component Node "
					+ this.getComponentFullKey(), e);
		} finally {
			if (rs != null) {
				rs.close();
			}
			if (statement != null) {
				statement.close();
			}
		}

		if ("true".equals(updateSucc)) {
			IDictItemInfo itemInfo = SaturnDictionaryManager.getInstance()
					.getDataDictItemInfo(type, code);

			itemInfo.setValue(value);
			itemInfo.setPinyin(pinyin);
		}

		parameterContext.setParameter(5, updateSucc);

	}
}
